package com.neu.credit.creditscore.service.hospital.impl;

import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.neu.credit.creditscore.common.utils.*;
import com.neu.credit.creditscore.dto.req.*;

import com.neu.credit.creditscore.dto.res.hospital.*;
import com.neu.credit.creditscore.entity.CreditScore;
import com.neu.credit.creditscore.entity.Transmissionjson;
import com.neu.credit.creditscore.entity.User;

import com.neu.credit.creditscore.entity.hospital.*;
import com.neu.credit.creditscore.mapper.CreditScoreMapper;
import com.neu.credit.creditscore.mapper.TransmissionjsonMapper;
import com.neu.credit.creditscore.mapper.UserMapper;
import com.neu.credit.creditscore.mapper.hospital.*;
import com.neu.credit.creditscore.service.KafkaProducerService;
import com.neu.credit.creditscore.service.hospital.DoctorsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.zachary.commonmodule.entity.MqTransmissionJson;

import java.math.BigDecimal;
import java.rmi.server.RemoteServer;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDateTime;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;


/**
 * <p>
 * 医生信息表 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-06-17
 */
@Slf4j
@Service
public class DoctorsServiceImpl extends ServiceImpl<DoctorsMapper, Doctors> implements DoctorsService {

    @Autowired
    private DoctorsMapper doctorsMapper;
    @Autowired
    private DepartmentsMapper departmentsMapper;
    @Autowired
    private AppointmentsMapper appointmentsMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private PrescriptionDrugsMapper prescriptionDrugsMapper;

    @Autowired
    private ExaminationItemsMapper examinationItemsMapper;

    @Autowired
    private ExaminationOrdersMapper examinationOrdersMapper;
    @Autowired
    private PrescriptionsMapper prescriptionsMapper;
    @Autowired
    private DiagnosisRecordsMapper diagnosisRecordsMapper;
    @Autowired
    private FeesMapper feesMapper;
    @Autowired
    private CreditScoreMapper creditScoreMapper;
    @Autowired
    private TransmissionjsonMapper transmissionjsonMapper;
    private static final Integer ServiceType_ComfortableMedicalTreatment=8;
    @Autowired
    private KafkaProducerService kafkaProducerService;
    @Override
    public  Doctors validateLogin(String phone, String password) {
        // 根据姓名查询医生
        LambdaQueryWrapper<Doctors> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Doctors::getPhone,  phone);
        Doctors  doctor=doctorsMapper.selectOne(queryWrapper);
        // 明文比较密码（实际项目必须加密！）
        if(doctor != null && doctor.getDoctorPassword().equals(password)){
            return doctor;
        }
        else  return null;
    }
    @Override
    public Result<List<RecommendDoctorsRes>> getRecommendDoctor() {
        try {
            LambdaQueryWrapper<Doctors> doctorQuery = new LambdaQueryWrapper<>();
            doctorQuery.eq(Doctors::getDoctorTitle, Doctors.DOCTOR_TITLE_CHIEF)
                    .orderByDesc(Doctors::getCreatedAt);
            List<Doctors> doctors = doctorsMapper.selectList(doctorQuery);

            List<Integer> departmentIds = doctors.stream()
                    .map(Doctors::getDepartmentId).distinct().collect(Collectors.toList());

            LambdaQueryWrapper<Departments> departmentQuery = new LambdaQueryWrapper<>();
            departmentQuery.in(Departments::getId, departmentIds);
            List<Departments> departmentsList = departmentsMapper.selectList(departmentQuery);

            Map<Integer, String> departmentIdNameMap = departmentsList.stream()
                    .collect(Collectors.toMap(Departments::getId, Departments::getDepartmentName, (v1, v2) -> v1));

            List<RecommendDoctorsRes> resList = doctors.stream().map(doctor -> {
                RecommendDoctorsRes res = new RecommendDoctorsRes();
                res.setDoctorId(doctor.getId());
                res.setDoctorName(doctor.getDoctorName());
                res.setDoctorTitle(doctor.getDoctorTitle().toString());
                res.setDoctorSpecialty(doctor.getDoctorSpecialty());
                res.setDepartmentName(departmentIdNameMap.get(doctor.getDepartmentId()));
                res.setImage(doctor.getImage());
                return res;
            }).collect(Collectors.toList());

            return Result.success(resList);

        } catch (Exception e) {
            log.error("getRecommendDoctor has a error", e);
            return Result.error("获取默认推荐的主任医生失败！");
        }
    }

    @Override
    public Result<List<Departments>> getDepartments(int departmentType) {
        try {
            LambdaQueryWrapper<Departments> departQuery = new LambdaQueryWrapper<>();
            departQuery.eq(Departments::getDepartmentType, departmentType)
                    .orderByDesc(Departments::getCreatedAt);
            List<Departments> departments = departmentsMapper.selectList(departQuery);

            return Result.success(departments);
        } catch (Exception e) {
            log.error("getDepartments has a error", e);
            return Result.error("获取科室失败！");
        }
    }

    @Override
    public Result<DoctorListInfoRes> getDoctors(int departmentId) {
        try {
            LambdaQueryWrapper<Doctors> doctorsQuery = new LambdaQueryWrapper<>();
            doctorsQuery.eq(Doctors::getDepartmentId, departmentId)
                    .orderByDesc(Doctors::getDoctorTitle)
                    .orderByDesc(Doctors::getCreatedAt);
            List<Doctors> doctors = doctorsMapper.selectList(doctorsQuery);

            Departments departments = departmentsMapper.selectById(departmentId);

            DoctorListInfoRes res = new DoctorListInfoRes();
            res.setDepartmentName(departments.getDepartmentName());
            res.setDoctorsList(doctors);

            return Result.success(res);

        } catch (Exception e) {
            log.error("getDoctors has a error", e);
            return Result.error("获取医生失败！");
        }
    }

    @Override
    public Result<Doctors> getDoctorsDetail(int doctorId) {
        try {
            Doctors doctors = doctorsMapper.selectById(doctorId);
            return Result.success(doctors);
        } catch (Exception e) {
            log.error("getDoctorsDetail has a error", e);
            return Result.error("获取医生详情失败！");
        }
    }

    @Override
    public Result<HospitalPreOrderInfoRes> getPreOrderInfo(HospitalPreOrderReq hospitalPreOrderReq,Integer userId) {
        try {
            LambdaQueryWrapper<Appointments> appointmentQuery = new LambdaQueryWrapper<>();
            appointmentQuery.eq(Appointments::getUserId, userId)
                    .eq(Appointments::getDoctorId, hospitalPreOrderReq.getDoctorId())
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_WAITING);
            Long existingCount = appointmentsMapper.selectCount(appointmentQuery);
            if (existingCount > 0) {
                return Result.error("您已经预约成功了，请按时就诊！");
            }
            //先将预约预下单的信息写进数据库当中
            Appointments appointment = new Appointments();
            appointment.setUserId(userId );
            appointment.setDoctorId(hospitalPreOrderReq.getDoctorId());
            appointment.setReason(hospitalPreOrderReq.getReason());
            appointment.setAppointmentStatus(Appointments.STATUS_PRE);
            //将预约信息返回给前端用户
            HospitalPreOrderInfoRes res = new HospitalPreOrderInfoRes();
            Doctors doctor = doctorsMapper.selectById(hospitalPreOrderReq.getDoctorId());
            res.setDoctorName(doctor.getDoctorName());
            appointment.setDepartmentId(doctor.getDepartmentId());
            appointment.setAppointmentTime(new Date());
            appointmentsMapper.insert(appointment);
            res.setAppointmentId(appointment.getId());
            Departments department = departmentsMapper.selectById(doctor.getDepartmentId());
            res.setDepartmentName(department.getDepartmentName());
            res.setCreatTimeStr(DateUtils.formatTime(new Date()));
            res.setAppointmentId(appointment.getId());
            Doctors  doctors=doctorsMapper.selectById(hospitalPreOrderReq.getDoctorId());
            Integer title = doctors.getDoctorTitle();
            if (title!=null) {
                switch (title) {
                    case 0:
                        res.setFee(20);
                        break;
                    case 1:
                        res.setFee(50);
                        break;
                    case 2:
                        res.setFee(80);
                        break;
                    default:
                        res.setFee(0);
                        break;
                }
            }
            User user = userMapper.selectById(userId);
            res.setUserInfo(user);
            LambdaQueryWrapper<CreditScore> query = new LambdaQueryWrapper<>();
            query.eq(CreditScore::getUserId, userId);
            CreditScore creditScore = creditScoreMapper.selectOne(query);
            res.setScore(creditScore.getScore());
            return Result.success(res);

        } catch (Exception e) {
            log.error("HospitalPreOrderInfoRes has a error", e);
            return Result.error("预下单失败！");
        }
    }

    @Override
    public Result<String> order(int appointmentId) {
        try {
            Appointments appointments = appointmentsMapper.selectById(appointmentId);
            appointments.setAppointmentStatus(Appointments.STATUS_WAITING);
            appointmentsMapper.updateById(appointments);

            return Result.success("预约成功！");

        } catch (Exception e) {
            log.error("order has a error", e);
            return Result.error("下单失败！");
        }
    }
    @Override
    public Result<List<MyAppointmentRes>> orderMyList(  Integer  userId) {
        try {

            LambdaQueryWrapper<Appointments> appointmentQuery = new LambdaQueryWrapper<>();
            appointmentQuery.eq(Appointments::getUserId, userId)
                    .orderByDesc(Appointments::getUpdatedAt);
            List<Appointments> appointments = appointmentsMapper.selectList(appointmentQuery);
            if (CollectionUtils.isEmpty(appointments)) {
                return Result.success(Collections.emptyList());
            }

            List<Integer> doctorIds = appointments.stream().distinct()
                    .map(Appointments::getDoctorId).collect(Collectors.toList());

            LambdaQueryWrapper<Doctors> doctorQuery = new LambdaQueryWrapper<>();
            doctorQuery.in(Doctors::getId, doctorIds);
            List<Doctors> doctors = doctorsMapper.selectList(doctorQuery);
            Map<Integer, Doctors> doctorIdMap = doctors.stream()
                    .collect(Collectors.toMap(Doctors::getId, Function.identity(), (v1, v2) -> v1));

            List<Integer> departmentIds = doctors.stream().distinct()
                    .map(Doctors::getDepartmentId).collect(Collectors.toList());
            LambdaQueryWrapper<Departments> departQuery = new LambdaQueryWrapper<>();
            departQuery.in(Departments::getId, departmentIds);
            List<Departments> departments = departmentsMapper.selectList(departQuery);
            Map<Integer, String> departIdNameMap = departments.stream()
                    .collect(Collectors.toMap(Departments::getId, Departments::getDepartmentName, (v1, v2) -> v1));

            List<MyAppointmentRes> resList = appointments.stream().map(appointment -> {
                MyAppointmentRes res = new MyAppointmentRes();
                res.setCreateTimeStr(DateUtils.formatTime(appointment.getCreatedAt()));
                Doctors doctor = doctorIdMap.get(appointment.getDoctorId());
                Integer departmentId = doctor.getDepartmentId();
                res.setDepartmentName(departIdNameMap.get(departmentId));
                res.setAppointmentId(appointment.getId());
                res.setDoctorName(doctor.getDoctorName());
                res.setDoctorTitleStr(doctor.getDoctorTitle().toString());
                res.setStatus(appointment.getAppointmentStatus());
                return res;
            }).collect(Collectors.toList());

            return Result.success(resList);
        } catch (Exception e) {
            log.error("orderMyList has a error", e);
            return Result.error("我的预约列表获取失败！");
        }
    }


    @Override
    public Result<List<PatientInfoRes>> getPatientsList(Integer doctorId) {
        try {
            // 1. 根据医生ID查询该医生的所有预约记录
            System.out.println(doctorId);
            LambdaQueryWrapper<Appointments> appointmentQuery = new LambdaQueryWrapper<>();
            appointmentQuery.eq(Appointments::getDoctorId, doctorId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_WAITING)
                    .orderByDesc(Appointments::getCreatedAt);
            List<Appointments> appointments = appointmentsMapper.selectList(appointmentQuery);

            for (Appointments appointment : appointments) {
                System.out.println(appointment.toString());
            }

            if (appointments.isEmpty()) {
                return Result.success(Collections.emptyList()); // 若无预约，直接返回空列表
            }

            // 2. 提取所有患者ID
            List<Integer> patientIds = appointments.stream()
                    .map(Appointments::getUserId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            if (patientIds.isEmpty()) {
                return Result.success(Collections.emptyList()); // 若无有效患者ID，返回空列表
            }

            // 3. 查询患者信息
            LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
            userQuery.in(User::getId, patientIds);
            List<User> users = userMapper.selectList(userQuery);


            Map<Long, User> userIdUserMap = users.stream()
                    .collect(Collectors.toMap(
                            User::getId,
                            Function.identity(),
                            (v1, v2) -> v1,
                            HashMap::new
                    ));
            System.out.println("患者信息");
            for (User user : users) {
                System.out.println(user.getNickName());
            }


            List<PatientInfoRes> resList = appointments.stream()
                    .map(appointment -> {
                        PatientInfoRes res = new PatientInfoRes();
                        res.setAppointments(appointment);


                        User user = userIdUserMap.getOrDefault(
                                appointment.getUserId() != null ? appointment.getUserId().longValue() : null,
                                null
                        );
                        res.setUser(user);

                        return res;
                    })
                    .collect(Collectors.toList());

            return Result.success(resList);
        } catch (Exception e) {
            return Result.error("获取患者列表失败！");
        }
    }
    @Override
    public Result<List<PatientInfoRes>> searchPatientsByName(Integer doctorId, String patientName) {
        try {

            // 1. 查询该医生的所有预约记录
            LambdaQueryWrapper<Appointments> appointmentQuery = new LambdaQueryWrapper<>();
            appointmentQuery.eq(Appointments::getDoctorId, doctorId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_WAITING)
                    .orderByDesc(Appointments::getCreatedAt);
            List<Appointments> appointments = appointmentsMapper.selectList(appointmentQuery);

            if (appointments.isEmpty()) {
                return Result.success(Collections.emptyList());
            }

            // 2. 提取所有患者ID（去重）
            List<Integer> patientIds = appointments.stream()
                    .map(Appointments::getUserId)
                    .filter(Objects::nonNull)
                    .distinct()
                    .collect(Collectors.toList());

            if (patientIds.isEmpty()) {
                return Result.success(Collections.emptyList());
            }

            // 3. 根据患者姓名模糊查询匹配的用户
            LambdaQueryWrapper<User> userQuery = new LambdaQueryWrapper<>();
            userQuery.in(User::getId, patientIds)
                    .like(User::getUsername, patientName); // 模糊匹配姓名
            List<User> matchedUsers = userMapper.selectList(userQuery);

            if (matchedUsers.isEmpty()) {
                return Result.success(Collections.emptyList());
            }

            // 4. 构建用户ID到用户对象的映射
            Map<Long, User> userIdUserMap = matchedUsers.stream()
                    .collect(Collectors.toMap(
                            User::getId,
                            Function.identity(),
                            (v1, v2) -> v1,
                            HashMap::new
                    ));

            // 5. 过滤并组装结果：仅保留匹配姓名的患者预约
            List<PatientInfoRes> resList = appointments.stream()
                    .filter(appointment -> appointment.getUserId() != null &&
                            userIdUserMap.containsKey(appointment.getUserId().longValue()))
                    .map(appointment -> {
                        PatientInfoRes res = new PatientInfoRes();
                        res.setAppointments(appointment);
                        res.setUser(userIdUserMap.get(appointment.getUserId().longValue()));
                        return res;
                    })
                    .collect(Collectors.toList());

            return Result.success(resList);
        } catch (Exception e) {
            return Result.error("查询患者失败！");
        }
    }

    @Override
    public Result<String> cancelAppoint(int appointmentId) {
        try {
            Appointments appointments = appointmentsMapper.selectById(appointmentId);
            appointments.setAppointmentStatus(Appointments.STATUS_CANCEL);
            appointmentsMapper.updateById(appointments);
            return Result.success("预约取消成功！");
        } catch (Exception e) {
            log.error("cancelAppoint has a error", e);
            return Result.error("取消预约失败！");
        }
    }

    @Override
    public Result<String> startCheck(int patientId, int doctorId)  {
        try {
            LambdaQueryWrapper<Appointments> appointmentQuery = new LambdaQueryWrapper<>();
            appointmentQuery.eq(Appointments::getUserId, patientId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_WAITING)
                    .eq(Appointments::getDoctorId, doctorId);
            Appointments appointments = appointmentsMapper.selectOne(appointmentQuery);
            appointments.setAppointmentStatus(Appointments.STATUS_USING);

            appointmentsMapper.updateById(appointments);

            return Result.success("开始接诊");


        } catch (Exception e) {
            log.error("startCheck has a error", e);
            return Result.error("开始接诊失败！");
        }
    }
    /**
     * 定时任务：每天凌晨2点检查一次24小时前完成诊疗的订单支付状态
     */

    @Component  // 确保类被Spring管理
    public class PaymentStatusCheckTask {
        @Autowired
        private AppointmentsMapper appointmentsMapper; // 注入预约信息Mapper

        @Autowired
        private FeesMapper feesMapper; // 注入费用信息Mapper

        @Autowired
        private TransmissionjsonMapper transmissionjsonMapper; // 注入传输JSON记录Mapper

        @Autowired
        private KafkaProducerService kafkaProducerService; // 注入Kafka消息生产者服务
        // 项目启动时执行一次（依赖注入完成后触发）
        @PostConstruct
        public void initCheck() {
            log.info("项目启动，触发支付状态检查任务");
            check24HourPaymentStatus();
        }

        // 每天凌晨2点定期执行
        @Scheduled(cron = "0 0 2 * * ?")
        public void check24HourPaymentStatus() {
            try {
                // 计算昨天同一时间点（24小时前）
                Date twentyFourHoursAgo = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
                // 计算前天同一时间点（48小时前）
                Date fortyEightHoursAgo = new Date(System.currentTimeMillis() - 48 * 60 * 60 * 1000);

                // 查询诊疗结束时间在24-48小时前的订单（确保只检查一次）
                LambdaQueryWrapper<Appointments> query = new LambdaQueryWrapper<>();
                query.eq(Appointments::getAppointmentStatus, Appointments.STATUS_DONE)
                        .ge(Appointments::getUpdatedAt, fortyEightHoursAgo)
                        .le(Appointments::getUpdatedAt, twentyFourHoursAgo);
                List<Appointments> appointments = appointmentsMapper.selectList(query);
                log.info(appointments.toString());
                List<Integer> appointmentIds = appointments.stream()
                        .map(Appointments::getId)
                        .collect(Collectors.toList());

                Map<Integer, Fees> feeMap = new HashMap<>();
                if (!appointmentIds.isEmpty()) {
                    LambdaQueryWrapper<Fees> feeQuery = new LambdaQueryWrapper<>();
                    feeQuery.in(Fees::getAppointmentId, appointmentIds);
                    feeMap = feesMapper.selectList(feeQuery).stream()
                            .collect(Collectors.toMap(Fees::getAppointmentId, fee -> fee));
                }

                // 处理结果
                for (Appointments appointment : appointments) {
                    Fees fee = feeMap.get(appointment.getId());
                    if (fee != null && fee.getPaymentStatus() == 0) {
                        appointment.setAppointmentStatus(Appointments.STATUS_OVERDUE);
                        appointmentsMapper.updateById(appointment);
                        // 当前费用记录的UUID（使用fee的ID作为标识）
                        String currentUuid = fee.getId().toString()+"hospital";

                        // 1. 检查transmissionjson表中是否已存在相同UUID
                        LambdaQueryWrapper<Transmissionjson> transmissionjsonquery = new LambdaQueryWrapper<>();
                        transmissionjsonquery.eq(Transmissionjson::getUuid, currentUuid);
                        Transmissionjson existing = transmissionjsonMapper.selectOne(transmissionjsonquery);

                        // 2. 如果已存在相同UUID，跳过发送逻辑
                        if (existing != null) {
                            continue; // 直接进入下一次循环
                        }

                        // 3. 不存在则插入transmissionjson并发送Kafka消息
                        Transmissionjson transmissionjson = new Transmissionjson();
                        transmissionjson.setUuid(currentUuid);
                        transmissionjson.setDueTime(Date.from(Instant.now()));
                        transmissionjsonMapper.insert(transmissionjson);
                        MqTransmissionJson json = new MqTransmissionJson(
                                fee.getId().toString()+"hospital",
                                appointment.getUserId(),
                                ServiceType_ComfortableMedicalTreatment,
                                true,
                                -1,
                                true,
                                -1,
                                "舒心就医信用分计算",
                                Instant.now(),
                                null
                        );
                        kafkaProducerService.sendJsonMessage(json);
                        log.info("发送消息到Kafka: {}", json);
                    }
                }

            } catch (Exception e) {
                log.error("支付状态检查任务执行失败", e);
            }
        }
    }
    @Override
    public Result<PatientInfoRes> getCheckNow() {
        try {
            LambdaQueryWrapper<Appointments> appointmentQuery = new LambdaQueryWrapper<>();
            appointmentQuery.eq(Appointments::getAppointmentStatus, Appointments.STATUS_USING)
                    .eq(Appointments::getDoctorId, BaseContext.getCurrentIUserId());
            Appointments appointments = appointmentsMapper.selectOne(appointmentQuery);

            Integer userId = appointments.getUserId();
            User user = userMapper.selectById(userId);

            return Result.success(new PatientInfoRes(user, appointments));

        } catch (Exception e) {
            log.error("getCheckNow has a error", e);
            return Result.error("获取失败！");
        }
    }

    @Override
    public Result<String> finishCheck(int patientId,int doctorId) {
        try {
            LambdaQueryWrapper<Appointments> appointQuery = new LambdaQueryWrapper<>();
            appointQuery.eq(Appointments::getUserId, patientId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_USING)
                    .eq(Appointments::getDoctorId, doctorId);
            Appointments appointments = appointmentsMapper.selectOne(appointQuery);
           int  appointmentId= appointments.getId();
            appointments.setAppointmentStatus(Appointments.STATUS_DONE);
            appointments.setUpdatedAt(new  Date());

            appointmentsMapper.updateById(appointments);
            LambdaQueryWrapper<ExaminationOrders> examOrderQuery = new LambdaQueryWrapper<>();
            examOrderQuery.eq(ExaminationOrders::getAppointmentId, appointmentId)
                    .orderByDesc(ExaminationOrders::getUpdatedAt);
            List<ExaminationOrders> examinationOrders = examinationOrdersMapper.selectList(examOrderQuery);
            List<Integer> examIds = examinationOrders.stream()
                    .distinct().map(ExaminationOrders::getItemId).collect(Collectors.toList());
            BigDecimal examFee = new BigDecimal(0);
            if(!examinationOrders.isEmpty()){
                LambdaQueryWrapper<ExaminationItems> itemQuery = new LambdaQueryWrapper<>();
                itemQuery.in(ExaminationItems::getId, examIds);
                List<ExaminationItems> examinationItems = examinationItemsMapper.selectList(itemQuery);
                Map<Integer, ExaminationItems> itemMap = examinationItems.stream()
                        .collect(Collectors.toMap(ExaminationItems::getId, item -> item));
                for (ExaminationOrders order : examinationOrders) {
                    order.setExaminationItem(itemMap.get(order.getItemId()));
                }
                Map<Integer, BigDecimal> itemPriceMap = examinationItems.stream()
                        .collect(Collectors.toMap(ExaminationItems::getId, ExaminationItems::getItemPrice, (v1, v2) -> v1));
                for (ExaminationOrders orders : examinationOrders) {
                    BigDecimal itemPrice = itemPriceMap.get(orders.getItemId());
                    examFee = examFee.add(itemPrice);
                }
            }

            LambdaQueryWrapper<Prescriptions> prescriptionsQuery = new LambdaQueryWrapper<>();
            prescriptionsQuery.eq(Prescriptions::getAppointmentId, appointmentId);
            List<Prescriptions> prescriptions = prescriptionsMapper.selectList(prescriptionsQuery);
            List<Integer> drugIds = prescriptions.stream().distinct().map(Prescriptions::getDrugId).collect(Collectors.toList());
            BigDecimal drugFee = new BigDecimal(0);
            if(!prescriptions.isEmpty()) {
                LambdaQueryWrapper<PrescriptionDrugs> drugsQuery = new LambdaQueryWrapper<>();
                drugsQuery.in(PrescriptionDrugs::getId, drugIds);
                List<PrescriptionDrugs> prescriptionDrugs = prescriptionDrugsMapper.selectList(drugsQuery);
                Map<Integer, BigDecimal> drugsIdPriceMap = prescriptionDrugs.stream()
                        .collect(Collectors.toMap(PrescriptionDrugs::getId, PrescriptionDrugs::getDrugPrice, (v1, v2) -> v1));

                for (Prescriptions prescription : prescriptions){
                    BigDecimal drugPrice= drugsIdPriceMap.get(prescription.getDrugId());
                    drugFee = drugFee.add(drugPrice);
                }

                Map<Integer, PrescriptionDrugs> drugMap = prescriptionDrugs.stream()
                        .collect(Collectors.toMap(PrescriptionDrugs::getId, drug -> drug));


                for (Prescriptions prescription : prescriptions) {
                    prescription.setDrugInfo(drugMap.get(prescription.getDrugId()));
                }
            }
            Fees fees = new Fees();
            fees.setAppointmentId(appointmentId);
            fees.setDrugFee(drugFee);
            fees.setExaminationFee(examFee);
            Doctors doctors=doctorsMapper.selectById(  appointmentsMapper.selectById(appointmentId).getDoctorId());
            Integer title = doctors.getDoctorTitle();
            if (title!=null) {
                switch (title) {
                    case 0:
                        fees.setDiagnosisFee(BigDecimal.valueOf(20));
                        break;
                    case 1:
                        fees.setDiagnosisFee(BigDecimal.valueOf(50));
                        break;
                    case 2:
                        fees.setDiagnosisFee(BigDecimal.valueOf(80));
                        break;
                    default:
                        fees.setDiagnosisFee(BigDecimal.valueOf(0));
                        break;
                }
            }
            fees.setPaymentStatus(0);
            LambdaQueryWrapper<CreditScore> query = new LambdaQueryWrapper<>();
            query.eq(CreditScore::getUserId, patientId);
            CreditScore creditScore = creditScoreMapper.selectOne(query);
            if  (creditScore.getScore()<=200){
                fees.setDiscount(BigDecimal.valueOf(0));
            }else if(creditScore.getScore()<=300){
                fees.setDiscount(BigDecimal.valueOf(20));
            } else if (creditScore.getScore()<=400) {
                fees.setDiscount( BigDecimal.valueOf(50));
            }else if (creditScore.getScore()<=500) {
                fees.setDiscount(BigDecimal.valueOf(80)) ;
            }else if (creditScore.getScore()>500){
                fees.setDiscount(BigDecimal.valueOf(100))  ;
            }
            fees.setTotalFee(drugFee.add(examFee).add(fees.getDiagnosisFee()));
            fees.setActualPayment(drugFee.add(examFee).add(fees.getDiagnosisFee()).subtract(fees.getDiscount()));
            LambdaQueryWrapper<Fees>  feesjsonquery = new LambdaQueryWrapper<>();
            feesjsonquery.eq( Fees::getAppointmentId, appointmentId);
            Fees existingFees = feesMapper.selectOne(feesjsonquery);
            if (existingFees == null) {
                feesMapper.insert(fees); // 不存在则插入
            }
            return Result.success("结束成功！");

        } catch (Exception e) {
            log.error("finishCheck has a error", e);
            return Result.error("结束失败！");
        }
    }

    @Override
    public Result<ExaminationInfoRes> getExamList(int departmentId, String itemName, int patientId) {
        try {
            LambdaQueryWrapper<ExaminationItems> examQuery = new LambdaQueryWrapper<>();
            examQuery.eq(departmentId != 0, ExaminationItems::getDepartmentId, departmentId)
                    .like(!itemName.equals(""), ExaminationItems::getItemName, itemName)
                    .orderByDesc(ExaminationItems::getCreatedAt);
            List<ExaminationItems> examinationItems = examinationItemsMapper.selectList(examQuery);
            return Result.success(new ExaminationInfoRes(patientId, examinationItems));
        } catch (Exception e) {
            log.error("getExamList has a error", e);
            return Result.error("获取项目列表失败！");
        }
    }

    @Override
    public Result<String> saveExamList(ExamSaveReq examSaveReq,Integer doctorId) {
        try {

            List<Integer> itemIdList = examSaveReq.getItemIdList();
            int patientId = examSaveReq.getPatientId();

            LambdaQueryWrapper<Appointments> appointQuery = new LambdaQueryWrapper<>();
            appointQuery.eq(Appointments::getUserId, patientId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_USING);
            Appointments appointments = appointmentsMapper.selectOne(appointQuery);
            Integer appointmentsId = appointments.getId();


            for (Integer itemId : itemIdList) {
                ExaminationOrders orders = new ExaminationOrders();
                orders.setDoctorId(doctorId);
                orders.setItemId(itemId);
                orders.setAppointmentId(appointmentsId);
                orders.setOrderStatus(1);
                examinationOrdersMapper.insert(orders);
            }

            return Result.success("保存成功");

        } catch (Exception e) {
            log.error("saveExamList has a error", e);
            return Result.error("保存失败！");
        }
    }

    @Override
    public Result<DrugInfoRes> getDrug(String drugName, int patientId) {
        try {
            LambdaQueryWrapper<PrescriptionDrugs> drugQuery = new LambdaQueryWrapper<>();
            drugQuery.like(!drugName.equals(""), PrescriptionDrugs::getDrugName, drugName)
                    .orderByDesc(PrescriptionDrugs::getCreatedAt);
            List<PrescriptionDrugs> prescriptionDrugs = prescriptionDrugsMapper.selectList(drugQuery);

            return Result.success(new DrugInfoRes(patientId, prescriptionDrugs));

        } catch (Exception e) {
            log.error("getDrug has a error", e);
            return Result.error("获取失败！");
        }
    }

    @Override
    public Result<String> saveDrug(DrugSaveReq drugSaveReq,Integer doctorId) {
        try {

            int patientId = drugSaveReq.getPatientId();
            List<DrugsUsage> drugsUsageList = drugSaveReq.getDrugsUsageList();

            LambdaQueryWrapper<Appointments> appointQuery = new LambdaQueryWrapper<>();
            appointQuery.eq(Appointments::getUserId, patientId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_USING);
            Appointments appointments = appointmentsMapper.selectOne(appointQuery);
            Integer appointmentsId = appointments.getId();

            for (DrugsUsage drugsUsage : drugsUsageList) {
                Prescriptions prescriptions = new Prescriptions();
                prescriptions.setAppointmentId(appointmentsId);
                prescriptions.setDoctorId(doctorId);
                prescriptions.setDrugId(drugsUsage.getDrugId());
                prescriptions.setDosage(drugsUsage.getDosage());
                prescriptions.setUsage1(drugsUsage.getUsage1());
                prescriptions.setPrescriptionStatus(1);
                prescriptionsMapper.insert(prescriptions);
            }

            return Result.success("保存成功！");


        } catch (Exception e) {
            log.error("saveDrug has a error", e);
            return Result.error("保存失败！");
        }
    }

    @Override
    public Result<String> saveDiagnosis(int patientId, String diagnosisResult ) {
        try {
            LambdaQueryWrapper<Appointments> appointQuery = new LambdaQueryWrapper<>();
            appointQuery.eq(Appointments::getUserId, patientId)
                    .eq(Appointments::getAppointmentStatus, Appointments.STATUS_USING);
            Appointments appointments = appointmentsMapper.selectOne(appointQuery);
            Integer appointmentsId = appointments.getId();

            DiagnosisRecords records = new DiagnosisRecords();
            records.setAppointmentId(appointmentsId);
            records.setDiagnosisResult(diagnosisResult);
            records.setDoctorId(appointments.getDoctorId());
            diagnosisRecordsMapper.insert(records);

            return Result.success("保存成功");
        } catch (Exception e) {
            log.error("saveDiagnosis has a error", e);
            return Result.error("保存失败！");
        }
    }

    @Override
    public Result<ResultDetailRes> getResultDetail(int appointmentId, Integer userId) {
        try {
            ResultDetailRes res = new ResultDetailRes();

            LambdaQueryWrapper<ExaminationOrders> examOrderQuery = new LambdaQueryWrapper<>();
            examOrderQuery.eq(ExaminationOrders::getAppointmentId, appointmentId)
                    .orderByDesc(ExaminationOrders::getUpdatedAt);
            List<ExaminationOrders> examinationOrders = examinationOrdersMapper.selectList(examOrderQuery);
            List<Integer> examIds = examinationOrders.stream()
                    .distinct().map(ExaminationOrders::getItemId).collect(Collectors.toList());
            BigDecimal examFee = new BigDecimal(0);
            if(!examinationOrders.isEmpty()){
                LambdaQueryWrapper<ExaminationItems> itemQuery = new LambdaQueryWrapper<>();
                itemQuery.in(ExaminationItems::getId, examIds);
                List<ExaminationItems> examinationItems = examinationItemsMapper.selectList(itemQuery);
                Map<Integer, ExaminationItems> itemMap = examinationItems.stream()
                        .collect(Collectors.toMap(ExaminationItems::getId, item -> item));
                for (ExaminationOrders order : examinationOrders) {
                    order.setExaminationItem(itemMap.get(order.getItemId()));
                }
                Map<Integer, BigDecimal> itemPriceMap = examinationItems.stream()
                        .collect(Collectors.toMap(ExaminationItems::getId, ExaminationItems::getItemPrice, (v1, v2) -> v1));
                for (ExaminationOrders orders : examinationOrders) {
                    BigDecimal itemPrice = itemPriceMap.get(orders.getItemId());
                    examFee = examFee.add(itemPrice);
                }
            }

            LambdaQueryWrapper<Prescriptions> prescriptionsQuery = new LambdaQueryWrapper<>();
            prescriptionsQuery.eq(Prescriptions::getAppointmentId, appointmentId);
            List<Prescriptions> prescriptions = prescriptionsMapper.selectList(prescriptionsQuery);
            List<Integer> drugIds = prescriptions.stream().distinct().map(Prescriptions::getDrugId).collect(Collectors.toList());
            BigDecimal drugFee = new BigDecimal(0);
            if(!prescriptions.isEmpty()) {
                LambdaQueryWrapper<PrescriptionDrugs> drugsQuery = new LambdaQueryWrapper<>();
                drugsQuery.in(PrescriptionDrugs::getId, drugIds);
                List<PrescriptionDrugs> prescriptionDrugs = prescriptionDrugsMapper.selectList(drugsQuery);
                Map<Integer, BigDecimal> drugsIdPriceMap = prescriptionDrugs.stream()
                        .collect(Collectors.toMap(PrescriptionDrugs::getId, PrescriptionDrugs::getDrugPrice, (v1, v2) -> v1));

                for (Prescriptions prescription : prescriptions){
                    BigDecimal drugPrice= drugsIdPriceMap.get(prescription.getDrugId());
                    drugFee = drugFee.add(drugPrice);
                }

                Map<Integer, PrescriptionDrugs> drugMap = prescriptionDrugs.stream()
                        .collect(Collectors.toMap(PrescriptionDrugs::getId, drug -> drug));


                for (Prescriptions prescription : prescriptions) {
                    prescription.setDrugInfo(drugMap.get(prescription.getDrugId()));
                }
            }
            Doctors doctors=doctorsMapper.selectById(  appointmentsMapper.selectById(appointmentId).getDoctorId());
            Integer title = doctors.getDoctorTitle();

            Appointments  appointment=appointmentsMapper.selectById(appointmentId);

            User user = userMapper.selectById(userId);
            LambdaQueryWrapper<DiagnosisRecords> recordQuery = new LambdaQueryWrapper<>();
            recordQuery.eq(DiagnosisRecords::getAppointmentId, appointmentId);
            DiagnosisRecords records = diagnosisRecordsMapper.selectOne(recordQuery);
          /*  LambdaQueryWrapper<CreditScore> query = new LambdaQueryWrapper<>();
            query.eq(CreditScore::getUserId, userId);
            CreditScore creditScore = creditScoreMapper.selectOne(query);
            if  (creditScore.getScore()<=200){
                fees.setDiscount(BigDecimal.valueOf(0));
            }else if(creditScore.getScore()<=300){
                fees.setDiscount(BigDecimal.valueOf(20));
            } else if (creditScore.getScore()<=400) {
                fees.setDiscount( BigDecimal.valueOf(50));
            }else if (creditScore.getScore()<=500) {
                fees.setDiscount(BigDecimal.valueOf(80)) ;
            }else if (creditScore.getScore()>500){
                fees.setDiscount(BigDecimal.valueOf(100))  ;
            }
            fees.setTotalFee(drugFee.add(examFee).add(fees.getDiagnosisFee()));
            fees.setActualPayment(drugFee.add(examFee).add(fees.getDiagnosisFee()).subtract(fees.getDiscount()));
            LambdaQueryWrapper<Fees>  feesjsonquery = new LambdaQueryWrapper<>();
            feesjsonquery.eq( Fees::getAppointmentId, appointmentId);
            Fees existingFees = feesMapper.selectOne(feesjsonquery);
            if (existingFees == null) {
                feesMapper.insert(fees); // 不存在则插入
            }*/
            LambdaQueryWrapper<Fees>  feesQuery = new LambdaQueryWrapper<>();
            feesQuery.eq(Fees::getAppointmentId, appointmentId);
            Fees fees = feesMapper.selectOne(feesQuery);
            res.setUser(user);
            res.setAppointments(appointment);
            res.setDiagnosisRecords(records);
            res.setOrders(examinationOrders);
            res.setPrescriptions(prescriptions);
            res.setReason(appointment.getReason());
            res.setDiagnosisResult(records.getDiagnosisResult());
            res.setFees(fees);
            return Result.success(res);
        } catch (Exception e) {
            log.error("getResultDetail has a error", e);
            return Result.error("获取失败！");
        }
    }


    @Override
    public Result<PreFeeRes> prePayFee(int appointmentId) {
        try {

            LambdaQueryWrapper<ExaminationOrders> examOrderQuery = new LambdaQueryWrapper<>();
            examOrderQuery.eq(ExaminationOrders::getAppointmentId, appointmentId)
                    .orderByDesc(ExaminationOrders::getUpdatedAt);
            List<ExaminationOrders> examinationOrders = examinationOrdersMapper.selectList(examOrderQuery);
            List<Integer> examIds = examinationOrders.stream()
                    .distinct().map(ExaminationOrders::getItemId).collect(Collectors.toList());
            BigDecimal examFee = new BigDecimal(0);
            if(!examinationOrders.isEmpty()){
                LambdaQueryWrapper<ExaminationItems> itemQuery = new LambdaQueryWrapper<>();
                itemQuery.in(ExaminationItems::getId, examIds);
                List<ExaminationItems> examinationItems = examinationItemsMapper.selectList(itemQuery);
                Map<Integer, BigDecimal> itemPriceMap = examinationItems.stream()
                        .collect(Collectors.toMap(ExaminationItems::getId, ExaminationItems::getItemPrice, (v1, v2) -> v1));
                for (ExaminationOrders orders : examinationOrders) {
                    BigDecimal itemPrice = itemPriceMap.get(orders.getItemId());
                    examFee = examFee.add(itemPrice);
                }
            }

            LambdaQueryWrapper<Prescriptions> prescriptionsQuery = new LambdaQueryWrapper<>();
            prescriptionsQuery.eq(Prescriptions::getAppointmentId, appointmentId);
            List<Prescriptions> prescriptions = prescriptionsMapper.selectList(prescriptionsQuery);
            List<Integer> drugIds = prescriptions.stream().distinct().map(Prescriptions::getDrugId).collect(Collectors.toList());
            BigDecimal drugFee = new BigDecimal(0);
            if(!prescriptions.isEmpty()) {
                LambdaQueryWrapper<PrescriptionDrugs> drugsQuery = new LambdaQueryWrapper<>();
                drugsQuery.in(PrescriptionDrugs::getId, drugIds);
                List<PrescriptionDrugs> prescriptionDrugs = prescriptionDrugsMapper.selectList(drugsQuery);
                Map<Integer, BigDecimal> drugsIdPriceMap = prescriptionDrugs.stream()
                        .collect(Collectors.toMap(PrescriptionDrugs::getId, PrescriptionDrugs::getDrugPrice, (v1, v2) -> v1));

                for (Prescriptions prescription : prescriptions){
                    BigDecimal drugPrice= drugsIdPriceMap.get(prescription.getDrugId());
                    drugFee = drugFee.add(drugPrice);
                }
            }


            Fees fees = new Fees();
            fees.setAppointmentId(appointmentId);
            fees.setDrugFee(drugFee);
            fees.setExaminationFee(examFee);
            fees.setTotalFee(drugFee.add(examFee));
            fees.setPaymentStatus(0);
            Doctors doctors=doctorsMapper.selectById(  appointmentsMapper.selectById(appointmentId).getDoctorId());
            Integer title = doctors.getDoctorTitle();
            if (title!=null) {
                switch (title) {
                    case 0:
                        fees.setDiagnosisFee(BigDecimal.valueOf(20));
                        break;
                    case 1:
                        fees.setDiagnosisFee(BigDecimal.valueOf(50));
                        break;
                    case 2:
                        fees.setDiagnosisFee(BigDecimal.valueOf(80));
                        break;
                    default:
                        fees.setDiagnosisFee(BigDecimal.valueOf(0));
                        break;
                }
            }
            fees.setTotalFee(drugFee.add(examFee).add(fees.getDiagnosisFee()));
            fees.setPaymentStatus(0);
            return Result.success(new PreFeeRes(drugFee.add(examFee).add(fees.getDiagnosisFee()).toString(), fees.getId()));
        } catch (Exception e) {
            log.error("prePayFee has a error", e);
            return Result.error("预支付失败！");
        }
    }
    @Override
    public Result<String> payFee(int feeId ) {
        try {
            Fees fees = feesMapper.selectById(feeId);
            fees.setPaymentStatus(1);
            feesMapper.updateById(fees);
            Integer appointmentId = fees.getAppointmentId();
            Appointments appointments = appointmentsMapper.selectById(appointmentId);
            appointments.setAppointmentStatus(Appointments.STATUS_END);
            appointmentsMapper.updateById(appointments);
            Date updatedAt = appointments.getUpdatedAt();
            Date date = new Date();
            MqTransmissionJson json=new MqTransmissionJson();
             json.setUuid(fees.getId().toString()+"hospital");
             json.setUserId(appointments.getUserId());
             json.setServiceType(ServiceType_ComfortableMedicalTreatment);
             json.setPaid(true);
             json.setAmount( fees.getTotalFee().doubleValue());
             json.setDesc( "舒心就医信用分计算");
             json.setFinishTime(Instant.now());

// 将 Date 转换为 Instant
            Instant updatedAtInstant = updatedAt.toInstant();
            Instant currentInstant = date.toInstant();

// 计算时间差
            Duration duration = Duration.between(updatedAtInstant, currentInstant);

            Long days = 0L;
// 获取时间差（天数）
             days = duration.toDays();

// 如果不足一天不算
            if (duration.toHours() < 24) {
                json.setOverdue(false);
                json.setDueTime(null);
            }else {
                json.setOverdue(true);
                LambdaQueryWrapper<Transmissionjson> transmissionjsonquery = new LambdaQueryWrapper<>();
                transmissionjsonquery.eq(Transmissionjson::getUuid,  fees.getId().toString()+"hospital");
                Transmissionjson transmissionjson=transmissionjsonMapper.selectOne(transmissionjsonquery);
                json.setDueTime(transmissionjson.getDueTime().toInstant());
            }
               if (days <=1) {
                json.setOverduePeriod(0);
                }else if (days <= 7) {
                    json.setOverduePeriod(1); // 1-7天为第1档
                } else if (days <= 14) {
                    json.setOverduePeriod(2); // 8-14天为第2档
                } else if (days <= 90) {
                    json.setOverduePeriod(3); // 15天-3个月为第3档
                } else {
                    json.setOverduePeriod(4); // 超过3个月归为第4档
                }
            kafkaProducerService.sendJsonMessage(json);
            return Result.success("支付成功！");
        }catch (Exception e){
            log.error("payFee has a error", e);
            return Result.error("支付失败！");
        }
    }

    @Override
    public Result<DepartmentPageRes> getDepartmentList(int pageNum, int pageSize, int departmentId, String departmentName) {
        try {

            LambdaQueryWrapper<Departments> departQuery = new LambdaQueryWrapper<>();
            departQuery.eq(departmentId != 0 , Departments::getId, departmentId)
                    .eq(!departmentName.equals(""), Departments::getDepartmentName, departmentName)
                    .orderByDesc(Departments::getUpdatedAt);

            Page<Departments> page = new Page<>(pageNum, pageSize);

            Page<Departments> departmentsPage = departmentsMapper.selectPage(page, departQuery);

            return Result.success(new DepartmentPageRes(departmentsPage.getTotal(), departmentsPage.getRecords()));

        }catch (Exception e){
            log.error("getDepartmentList has a error", e);
            return Result.error("获取科室失败！");
        }
    }

    @Override
    public Result<String> addDepartment(AddDepartmentReq addDepartmentReq) {
        try {
            Departments departments = new Departments();
            departments.setDepartmentName(addDepartmentReq.getDepartmentName());
            departments.setDepartmentIntroduction(addDepartmentReq.getDepartmentIntroduction());
            departments.setDepartmentType(addDepartmentReq.getDepartmentType());
            departmentsMapper.insert(departments);
            return Result.success("添加成功！");

        }catch (Exception e){
            log.error("addDepartment has a error", e);
            return Result.error("添加科室失败！");
        }
    }

    @Override
    public Result<Departments> getDepartmentDetail(int departmentId) {
        try {
            Departments departments = departmentsMapper.selectById(departmentId);
            return Result.success(departments);
        }catch (Exception e){
            log.error("getDepartmentDetail has a error", e);
            return Result.error("获取科室详情失败失败！");
        }
    }

    @Override
    public Result<String> updateDepartment(Departments departments) {
        try {
            departmentsMapper.updateById(departments);
            return Result.success("编辑失败！");
        }catch (Exception e){
            log.error("updateDepartment has a error", e);
            return Result.error("编辑失败！");
        }
    }

    @Override
    public Result<String> deletedDepartment(int departmentId) {
        try {
            departmentsMapper.deleteById(departmentId);
            return Result.success("删除成功！");
        }catch (Exception e){
            log.error("deletedDepartment has a error", e);
            return Result.error("删除失败！");
        }
    }

    @Override
    public Result<DoctorListRes> getDoctorList(int pageNum, int pageSize, int doctorId, String doctorName) {
        try {
            LambdaQueryWrapper<Doctors> doctorQuery = new LambdaQueryWrapper<>();
            doctorQuery.eq( doctorId != 0 , Doctors::getId, doctorId)
                    .like(!doctorName.equals(""), Doctors::getDoctorName, doctorName)
                    .orderByDesc(Doctors::getUpdatedAt);

            Page<Doctors> page = new Page<>(pageNum, pageSize);
            Page<Doctors> doctorsPage = doctorsMapper.selectPage(page, doctorQuery);

            List<Doctors> doctors = doctorsPage.getRecords();
            List<Integer> departmentIds = doctors.stream().map(Doctors::getDepartmentId)
                    .distinct().collect(Collectors.toList());

            LambdaQueryWrapper<Departments> departQuery = new LambdaQueryWrapper<>();
            departQuery.in(Departments::getId, departmentIds);
            List<Departments> departments = departmentsMapper.selectList(departQuery);
            Map<Integer, Departments> departIdDepartMap = departments.stream()
                    .collect(Collectors.toMap(Departments::getId, Function.identity(), (v1, v2) -> v1));

            List<DoctorExtend> doctorList = doctors.stream().map(doctor -> {
                DoctorExtend extend = new DoctorExtend();
                BeanUtils.copyProperties(doctor, extend);
                Integer departmentId = doctor.getDepartmentId();
                Departments department = departIdDepartMap.get(departmentId);
                extend.setDepartmentName(department.getDepartmentName());
                return extend;
            }).collect(Collectors.toList());


            return Result.success(new DoctorListRes(doctorsPage.getTotal(), doctorList));


        }catch (Exception e){
            log.error("getDoctorList has a error", e);
            return Result.error("获取失败！");
        }
    }
    @Override
    public Result<Doctors> getDoctorDetail(int doctorId) {
        try {
            Doctors doctors = doctorsMapper.selectById(doctorId);
            return Result.success(doctors);
        }catch (Exception e){
            log.error("getDoctorDetail has a error", e);
            return Result.error("获取失败！");
        }
    }

    @Override
    public Result<String> addDoctor(Doctors doctors ) {
        try {
            doctorsMapper.insert(doctors);
            return Result.success("添加成功！");
        }catch (Exception e){
            log.error("addDoctor has a error", e);
            return Result.error("添加失败！");
        }
    }




    @Override
    public Result<String> deletedDoctor(int doctorId) {

        try {
            doctorsMapper.deleteById(doctorId);
            return Result.success("删除失败！");
        } catch (Exception e) {
            log.error("deletedBook has a error", e);
            return Result.error("删除失败！");
        }
    }


    @Override
    public Result<String> updateDoctor(Doctors doctors ) {
        try {
            doctorsMapper.updateById(doctors);
            return Result.success("编辑成功！");
        } catch (Exception e){
            log.error("updateDoctor has a error", e);
            return Result.error("编辑失败！");
        }
    }


}
